package com.soilflow.web.controller.system;

import com.soilflow.common.annotation.Log;
import com.soilflow.common.constant.Constants;
import com.soilflow.common.constant.UserConstants;
import com.soilflow.common.core.controller.BaseController;
import com.soilflow.common.core.domain.AjaxResult;
import com.soilflow.common.core.domain.entity.GamesUserScore;
import com.soilflow.common.core.domain.entity.SysRole;
import com.soilflow.common.core.domain.entity.SysUser;
import com.soilflow.common.core.domain.entity.SysUserReception;
import com.soilflow.common.core.domain.model.RegisterBody;
import com.soilflow.common.core.page.TableDataInfo;
import com.soilflow.common.enums.BusinessType;
import com.soilflow.common.utils.MessageUtils;
import com.soilflow.common.utils.NoUtils;
import com.soilflow.common.utils.SecurityUtils;
import com.soilflow.common.utils.StringUtils;
import com.soilflow.common.utils.poi.ExcelUtil;
import com.soilflow.framework.manager.AsyncManager;
import com.soilflow.framework.manager.factory.AsyncFactory;
import com.soilflow.know.service.GamesUserScoreService;
import com.soilflow.system.service.ISysConfigService;
import com.soilflow.system.service.ISysPostService;
import com.soilflow.system.service.ISysRoleService;
import com.soilflow.system.service.ISysUserReceptionService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author soilflow
 */
@RestController
@RequestMapping("/reception/user")
public class SysUserReceptionController extends BaseController
{
    @Autowired
    private ISysUserReceptionService userReceptionService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private GamesUserScoreService gamesUserScoreService;
    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user_reception:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUserReception user)
    {
        startPage();
        List<SysUserReception> list = userReceptionService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/all")
    public AjaxResult listAll()
    {
        List<SysUserReception> list = userReceptionService.selectUserList(new SysUserReception());
        return AjaxResult.success(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user_reception:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUserReception user)
    {
        List<SysUserReception> list = userReceptionService.selectUserList(user);
        ExcelUtil<SysUserReception> util = new ExcelUtil<SysUserReception>(SysUserReception.class);
        util.exportExcel( list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user_reception:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUserReception> util = new ExcelUtil<SysUserReception>(SysUserReception.class);
        List<SysUserReception> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userReceptionService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel( "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user_reception:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        userReceptionService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            SysUserReception  sysUser = userReceptionService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping("/phone/{phone}")
    public AjaxResult getByPhone(@PathVariable(value = "phone") String phone)
    {
        SysUserReception user = userReceptionService.getPhonenumber(phone);
        return AjaxResult.success(user);
    }


    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user_reception:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add( @RequestBody SysUserReception user)
    {
        System.out.println("user111"+user);
        if (UserConstants.NOT_UNIQUE.equals(userReceptionService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userReceptionService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userReceptionService.checkEmailUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCode(NoUtils.getUserCode());
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));



        int res = userReceptionService.insertUser(user);


        SysUserReception userData = userReceptionService.selectUserByUserName(user.getUserName());
        GamesUserScore gamesUserScore = new GamesUserScore();
        gamesUserScore.setUserId(userData.getUserId());
        gamesUserScore.setLastUpdateTime(new Date());
        gamesUserScore.setScore(BigDecimal.ZERO);
        gamesUserScore.setUserName(userData.getUserName());
        gamesUserScoreService.save(gamesUserScore);

        return toAjax(res);
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user_reception:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUserReception user)
    {
        userReceptionService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userReceptionService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userReceptionService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userReceptionService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user_reception:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userReceptionService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user_reception:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUserReception user)
    {
        userReceptionService.checkUserAllowed(user);
        userReceptionService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userReceptionService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user_reception:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUserReception user)
    {
        userReceptionService.checkUserAllowed(user);
        userReceptionService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userReceptionService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user_reception:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUserReception user = userReceptionService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user_reception:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userReceptionService.checkUserDataScope(userId);
        userReceptionService.insertUserAuth(userId, roleIds);
        return success();
    }
    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody registerBody)
    {

        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }

        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (UserConstants.NOT_UNIQUE.equals(userReceptionService.checkUserNameUnique(username)))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        else
        {
            SysUserReception sysUserReception = new SysUserReception();
            sysUserReception.setUserName(username);
            sysUserReception.setCode(NoUtils.getUserCode());
            if (!StringUtils.isEmpty( registerBody.getPhoneNumber()))
            {
                sysUserReception.setPhonenumber(registerBody.getPhoneNumber());
            }
            if (!StringUtils.isEmpty( registerBody.getEmail()))
            {
                sysUserReception.setEmail(registerBody.getEmail());
            }
            sysUserReception.setNickName(username);
            sysUserReception.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
            System.out.println(sysUserReception);
            boolean regFlag = userReceptionService.registerUser(sysUserReception);
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER,
                        MessageUtils.message("user.register.success")));
            }
        }        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }
}
